//时间格式转换
(function($) {
    $.extend({
        myTime: {
            /**
             * 当前时间戳
             * @return <int>        unix时间戳(秒)  
             */
            CurTime: function(){
                return Date.parse(new Date())/1000;
            },
            /**              
             * 日期 转换为 Unix时间戳
             * @param <string> 2014-01-01 20:20:20  日期格式              
             * @return <int>        unix时间戳(秒)              
             */
            DateToUnix: function(string) {
                var f = string.split(' ', 2);
                var d = (f[0] ? f[0] : '').split('-', 3);
                var t = (f[1] ? f[1] : '').split(':', 3);
                return (new Date(
                        parseInt(d[0], 10) || null,
                        (parseInt(d[1], 10) || 1) - 1,
                        parseInt(d[2], 10) || null,
                        parseInt(t[0], 10) || null,
                        parseInt(t[1], 10) || null,
                        parseInt(t[2], 10) || null
                        )).getTime() / 1000;
            },
            /**              
             * 时间戳转换日期              
             * @param <int> unixTime    待时间戳(秒)              
             * @param <bool> isFull    返回完整时间(Y-m-d 或者 Y-m-d H:i:s)              
             * @param <int>  timeZone   时区              
             */
            UnixToDate: function(unixTime, isFull, timeZone) {
                if (typeof (timeZone) == 'number')
                {
                    unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
                }
                var time = new Date(unixTime * 1000);
                var ymdhis = "";
                ymdhis += time.getUTCFullYear() + "-";
                ymdhis += (time.getUTCMonth()+1) + "-";
                ymdhis += time.getUTCDate();
                if (isFull === true)
                {
                    ymdhis += " " + time.getUTCHours() + ":";
                    ymdhis += time.getUTCMinutes() + ":";
                    ymdhis += time.getUTCSeconds();
                }
                return ymdhis;
            }
        }
    });
})(jQuery);

function CheckAll(form){
  for (var i=0;i<form.elements.length;i++){
    var e = form.elements[i];
  	if (e.name != 'chkall'){
	e.checked = form.checkall.checked;
	}
   }
}  
function ajaxForm(){
	//ajaxform
	var options = { 
		beforeSubmit:showRequest,//表单验证方式
        success:showResponse  // post-submit callback 
    }; 
    $('#ajaxForm').ajaxForm(options); 

    function showResponse(responseText, statusText)  {
    	//$("#myBtn").button('reset');
		if (statusText == 'success') {
			var responseText=eval('('+responseText+')');
			if(responseText.state == 'SUCCESS'){
				_alert2('SUCCESS',responseText.message,responseText.url);
			}else{
				_alert2('ERROR',responseText.state);
			}			
		}
	} 

	function showRequest(){
		 validata = $("form.form-validata").valid();
		 if (validata){
		 	//alert(1);
		 	//$("#myBtn").button('loading').html('<i class="fa fa-spinner fa-spin"></i> loading');
		 }
		 return validata;
	}
	//validation验证
	$("form.form-validata").validate({
		errorElement: "span",
        errorClass: "error",
        errorPlacement: function(error, element) {
        	element.parents(".form-group").addClass("has-error").append(error);
		},
		success:function(element){
	        element.parent().removeClass("has-error");
	    },
	})
}

//验证电话
function testPhone(v){
    if(v==""){
        return false;
    }else{
        var pattern = /^((?:\d{9})|(?:\d{3}-\d{4})|(?:\d{3}-\d{3}-\d{4})|[0-9]{10})$/;
        flag = pattern.test(v);
        if(!flag){
            return false;
        }else{
            return true;
        }
    }
}

//验证英文
function testEn(v){
    if(v==""){
        return false;
    }else{
        var pattern = /^[a-zA-Z0-9. ]+$/;
        flag = pattern.test(v);
        if(!flag){
            return false;
        }else{
            return true;
        }
    }
}

//验证区号
function testZip(v){
    if(v==""){
        return false;
    }else{
        var pattern = /^([0-9]{5})$/;
        flag = pattern.test(v);
        if(!flag){
            return false;
        }else{
            return true;
        }
    }
}

//密码

function testPass(str){

    var rC = {

        lW:'[a-z]',

        uW:'[A-Z]',

        nW:'[0-9]',

        sW:'[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'

    };

    function Reg(str, rStr){

        var reg = new RegExp(rStr);

        if(reg.test(str)) return true;

        else return false;

    }

    if(str.length < 8){

        //document.title = '您的密码长度太短';

        return false;

    }else{

        var tR = {

            l:Reg(str, rC.lW),

            u:Reg(str, rC.uW),

            n:Reg(str, rC.nW),

            s:Reg(str, rC.sW)

        };

        if((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s) || (tR.s && tR.u && tR.n) || (tR.s && tR.l && tR.n)){

            //document.title = '密码符合要求';

            return true;

        }else{

            //document.title = '您的密码必须含有“小写字母”、“大写字母”、“数字”、“特殊符号”中的任意三种';

            return false;

        }

    }

}

//重写alert弹窗
function _alert(msg,url){
	var title=title?title:"message box";
	var html='<div class="modal fade bs-example-modal-sm" tabindex="-1" id="my-alert" role="dialog" aria-labelledby="mySmallModalLabel">\
				  <div class="modal-dialog modal-sm">\
                    <div class="modal-content">\
					    <div class="modal-header">\
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\
                            <h5 class="modal-title" id="mySmallModalLabel">'+title+'</h5>\
                        </div>\
                        <div class="modal-body alertInfo">'+msg+'</div>\
                    </div>\
				  </div>\
				</div>';
	$(document.body).append(html);
	var $modal=$("#my-alert");
    $modal.modal({
    	backdrop: 'static',
		keyboard: false,
	},'show');
    $modal.on("hidden.bs.modal", function() {
        $modal.remove();
        if(url!='' && url!=undefined && url!="undefined"){
            window.location.href = url;     
        }
    })
}

function _alert2(state,message,url){
	var formDialog = art.dialog({lock : true});
	if(state == 'SUCCESS'){
		formDialog.content(message);
		formDialog.title('SUCCESS');
		formDialog.icon('succeed');
		var timer,i=2;
		var fn = function () {
			formDialog.title(i + ' seconds after close');
			if (!i){
				formDialog.close();
				clearInterval(timer);
				if(url==''){
					window.location.reload();
				}else{
					window.location.href = url;	
				}
			}
			i --;
		};
		timer = setInterval(fn, 1000);
	}else{
		formDialog.content(message);
		formDialog.title(state);
		formDialog.icon('error');
	}
}

function uploadImage(url , domid){
	art.dialog.data('domid', domid);
	art.dialog.open(url,{
	lock:true,
	title:'upload',
	width:500,
	height:300,
	});
}

function openWindow(title , url , width , height , domid){
	var width=width?width:600;
	var height=height?height:500;
	art.dialog.data('domid', domid);
	art.dialog.open(url,{
	lock:true,
	title:title,
	width:width,
	height:height,
	});
}

//发站内信
function sendMsg(uID,uName){
	$.get('/index.php?m=Mentees&c=Public&a=sendmsg',{toid:uID},function(data){
			intModal("To："+uName,data);
			ajaxForm();
		}
	);
}
//拜师
function apply(uID,uName){
	$.get('/index.php?m=Mentees&c=Public&a=apply',{toid:uID},function(data){
			intModal("To："+uName,data);
			ajaxForm();
		}
	);
}

//调取聊天窗口
function chat(uid){
	$.get('/index.php?m=Mentees&c=Public&a=chat',{toid:uid},function(data){
			intModal("Instant Chat",data);
		}
	);
}

//评价窗口
function comment(uid,uName){
	$.get('/index.php?m=Mentees&c=Public&a=comment',{toid:uid},function(data){
			intModal("To："+uName,data);
			ajaxForm();
		}
	);
}

//添加需求
function addneed(){
	$.get('/index.php?m=Mentees&c=Need&a=add',{},function(data){
			intModal("Release requirements",data);
			ajaxForm();
		}
	);
}

//发起预约需求
function appointment(uid){
	$.get('/index.php?m=Mentees&c=appointment&a=add',{toid:uid},function(data){
			intModal("Appointment",data);
			ajaxForm();
		}
	);
}


//初始化弹窗
function intModal(title,content){
	//var oldTit=$('#myModal .modal-title').text();
	$('#myModal .modal-title').text(title);
	$('#myModal .modal-body').html(content);
	$('#myModal').modal('show').on('hidden.bs.modal', function (e) {
	   //$('#myModal .modal-title').text(oldTit);
	   $(".modal-body").html('<div class="loading"><i class="fa fa-spinner fa-spin fa-4x"></i> loading...</div>');
	})
}


//***********************************在线及时聊天js****************************************************/

//创建聊天信息html
function createChatMsgHtml(data,uid){
	var html="";
	 for (var i = 0; i <data.length; i++) {
		if(data[i].fromID==uid){
			html+='<div class="conversation-item item-right clearfix">'+
					'<div class="conversation-user">'+
							'<img style="width:50px;height:50px;" src="'+data[i].fromFace+'" alt=""/>'+
						'</div>'+
						'<div class="conversation-body">'+
							'<div class="name">'+data[i].fromName+'</div>'+
							'<div class="time hidden-xs"> '+$.myTime.UnixToDate(data[i].createTime,true,8)+'</div>'+
							'<div class="text">'+data[i].content+'</div>'+
						'</div>'+
					'</div>';	
		}else{
			html+='<div class="conversation-item item-left clearfix">'+
					'<div class="conversation-user">'+
							'<img style="width:50px;height:50px;" src="'+data[i].fromFace+'" alt=""/>'+
						'</div>'+
						'<div class="conversation-body">'+
							'<div class="name">'+data[i].fromName+'</div>'+
							'<div class="time hidden-xs"> '+$.myTime.UnixToDate(data[i].createTime,true,8)+'</div>'+
							'<div class="text">'+data[i].content+'</div>'+
						'</div>'+
					'</div>';
		}
	 }
	return html;
}

